﻿using System.Collections.Concurrent;

namespace Thread_SafeCollections;

class Program
{
    // 示例：多个任务向同一个集合添加数据
    static void DemonstrateConcurrentCollections()
    {
        // 非线程安全的 List，多线程并发 Add 会有问题
        // List<int> unsafeList = new List<int>();

        // 线程安全的 ConcurrentBag
        ConcurrentBag<int> bag = new ConcurrentBag<int>();
        Parallel.For(0, 100, i =>
        {
            // unsafeList.Add(i); // 在 Parallel.For 中执行此操作会引发问题
            bag.Add(i); // ConcurrentBag 支持多线程安全添加
        });
        Console.WriteLine("Count: {0}", bag.Count);
    }

    // 示例：使用 ConcurrentDictionary 进行并发计数
    static void DemonstrateCollections()
    {
        ConcurrentDictionary<String, int> dict = new ConcurrentDictionary<String, int>();
        string[] words = { "apple", "banana", "apple", "orange", "banana", "apple" };
        Parallel.ForEach(words, word =>
        {
            // 使用 AddOrUpdate 安全地更新或添加键值对
            dict.AddOrUpdate(word, 1, (k, i) => i + 1);
        });
        Console.WriteLine($"单词计数：");
        foreach (var pair in dict)
        {
            Console.WriteLine($"{pair.Key}: {pair.Value}");
        }
    }

    static void Main(string[] args)
    {
        DemonstrateConcurrentCollections();
        DemonstrateCollections();
        Console.WriteLine("Hello, World!");
    }
}